import React, { useEffect, useMemo, useState } from 'react';
import { mapTreeData } from '@/utils/tree';
import { Button } from 'antd';
import SearchTree from '@/pages/Organization/OrgFlow/Department/components/SearchTree';
import { getTreeNodePath } from '@/components/CityPicker/utils';
import Animate from 'rc-animate';
import IconFont from '@/components/IconFont';
import EmployeeSelector from './EmployeeSelector';
import styles from './index.less';

// 员工调整选择器
const EmployeeTransfer = props => {
    const { treeData, allLeaves, onChange, basePath } = props;
    const allLeavesMap = useMemo(() => allLeaves.reduce((total, item) => ({ ...total, [item.id]: item }), {}), [
        allLeaves
    ]);
    const targetTreeData = useMemo(
        () =>
            mapTreeData(treeData || [], item => ({
                ...item,
                selectable: !item.children
            })),
        [treeData]
    );

    // 是否显示目标节点面板
    const [isShowTargetPanel, setIsShowTargetPanel] = useState(false);
    const [selectedEmployees, setSelectedEmployees] = useState([]);
    // 选中的目标节点
    const [selectedTargetNode, setSelectedTargetNode] = useState(null);

    useEffect(() => {
        if (selectedEmployees.length === 0) {
            setIsShowTargetPanel(false);
        }
    }, [selectedEmployees]);

    // 取消按钮事件
    const handleCancel = () => {
        setIsShowTargetPanel(false);
        setSelectedTargetNode(null);
    };

    // 确定按钮事件
    const handleConfirm = () => {
        const toOrgPathNodes = getTreeNodePath(treeData, selectedTargetNode.id);
        const toOrgPathCode = toOrgPathNodes?.map(item => item.organizationCode) || [];
        const toOrgPathName = toOrgPathNodes?.map(item => item.organizationName) || [];
        const result = selectedEmployees.map(id => {
            const node = allLeavesMap[id];
            const fromOrgPathNodes = getTreeNodePath(treeData, node.organizationCode, 'organizationCode');
            const fromOrgPathName = fromOrgPathNodes?.map(item => item.organizationName) || [];
            const fromOrgPathCode = fromOrgPathNodes?.map(item => item.organizationCode) || [];
            return {
                employeeCode: node.employeeCode,
                employeeName: node.employeeName,
                fromOrgCode: node.organizationCode,
                fromOrgName: node.organizationName,
                fromOrgPathCode: fromOrgPathCode.join('/'),
                fromOrgPathName: fromOrgPathName.join('/'),
                // fromFullOrgPathCode: 'TODO',
                fromFullOrgPathName: [basePath, ...fromOrgPathName].join('/'),
                fromDutyCode: node.dutyCode,
                fromDutyName: node.dutyAlias,
                toOrgCode: selectedTargetNode.organizationCode,
                toOrgName: selectedTargetNode.organizationName,
                toOrgPathCode: toOrgPathCode.join('/'),
                toOrgPathName: toOrgPathName.join('/'),
                // toFullOrgPathCode: 'TODO',
                toFullOrgPathName: [basePath, ...toOrgPathName].join('/')
                // toDutyCode: 'TODO',
                // toDutyName: 'TODO',
            };
        });
        onChange(result);
        // reset
        setIsShowTargetPanel(false);
        setSelectedTargetNode(null);
        setSelectedEmployees([]);
    };

    const renderSelector = () => (
        <EmployeeSelector treeData={targetTreeData} value={selectedEmployees} onChange={setSelectedEmployees} />
    );

    const renderRight = () => (
        <div className={styles.employeeTransferRight}>
            <Animate transitionName="slide-left-solid">
                {isShowTargetPanel && (
                    <div className={styles.rightTree}>
                        <SearchTree
                            value={selectedTargetNode?.id}
                            placeholder="搜索机构"
                            onChange={(key, node) => setSelectedTargetNode(node)}
                            treeData={targetTreeData}
                        />
                        <div className={styles.rightTreePanelControl}>
                            <Button type="default" onClick={handleCancel}>
                                取消
                            </Button>
                            &emsp;
                            <Button type="primary" onClick={handleConfirm} disabled={!selectedTargetNode}>
                                确定
                            </Button>
                        </div>
                    </div>
                )}
            </Animate>
        </div>
    );

    return (
        <div className={styles.employeeTransfer}>
            <div className={styles.employeeTransferLeft}>
                {renderSelector()}
                <Button
                    type="primary"
                    disabled={selectedEmployees.length === 0}
                    className={styles.changeGroup}
                    onClick={() => setIsShowTargetPanel(true)}
                >
                    <IconFont icon="iconzhuangtaibiangeng" style={{ fontSize: 20, verticalAlign: -2 }} />
                    变更机构
                </Button>
            </div>
            {renderRight()}
        </div>
    );
};

EmployeeTransfer.displayName = 'EmployeeTransfer';

export default EmployeeTransfer;
